<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "{{%module}}".
 *
 * @property int $id 主键
 * @property string $name 模块名
 * @property string $icon icon
 * @property int $sort 倒序排序
 * @property int $is_show 1 显示 2显示
 * @property int $create_time 添加时间
 * @property string $create_user 添加人
 */
class Module extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%module}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'icon', 'create_time', 'create_user'], 'required'],
            [['sort', 'create_time','is_show'], 'integer'],
            [['name', 'icon', 'create_user'], 'string', 'max' => 20],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '主键',
            'name' => '模块名',
            'icon' => 'icon',
            'sort' => '倒序排序',
            'is_show' => '1 显示 2显示',
            'create_time' => '添加时间',
            'create_user' => '添加人',
        ];
    }

    public function getMenu()
    {
        $menuIds = $this->getMenuIds();
        return $this->hasMany(Menu::className(),['module_id'=>'id'])
            ->where(['in','ht_menu.id',$menuIds])
            ->andWhere(['ht_menu.is_show'=>1])
            ->orderBy('ht_menu.sort desc');
    }

    /**
     * 根据路由返回菜单ID
     */
    public function getMenuIds()
    {
        $role = Role::findOne(Yii::$app->user->identity->role_id);
        $ids = json_decode($role->jurisdiction);
        $route = Route::find()->where(['in','id',$ids])->asArray()->all();
        $menuIds = array_unique(array_column($route,'menu_id'));//保持唯一
        return $menuIds;
    }
}
